package main

import "C"
import (
	"fmt"
	"gitee.com/zhaojh329/go-btstack"
	"os"
	"time"
)

func main() {
	btstack.StdinSetup(stdinProcess)

	btstack.HciDumpOpen("hci_dump.pklg", btstack.HciDumpPacketlogger)

	btstack.MemoryInit()

	btstack.RunLoopInit(btstack.RunLoopWindowsGetInstance())

	btstack.HciInit(btstack.HciTransportUsbInstance(), nil)

	btstack.L2capInit()

	btstack.SmInit()

	btstack.SmSetIoCapabilities(btstack.IoCapabilityNoInputNoOutput)

	btstack.LeDeviceDbInit()

	btstack.HciSetEventHandler(packetHandler)

	btstack.GapRandomAddressSetMode(btstack.GapRandomAddressNonResolvable)

	btstack.HciPowerControl(btstack.HciPowerOn)

	btstack.RunLoopExecute()
}

func packetHandler(packet interface{}) {
	switch packet := packet.(type) {
	case *btstack.EventPoweronFailedPacket:
		fmt.Println("Poweron failed")
		btstack.HciClose()
		os.Exit(1)
	case *btstack.EventStatePacket:
		if packet.State() == btstack.HciStateWorking {
			baddr := btstack.GapLocalBdAddr()
			fmt.Println("BTstack activated, get started: ", baddr)

			btstack.AttDbUtilInit()
			btstack.AttDbUtilAddServiceUuid16(0x1000)
			btstack.AttDbUtilAddCharacteristicUuid16(0x1001, btstack.AttPropertyRead|btstack.AttPropertyWriteWithoutResponse, btstack.AttSecurityNone,
				btstack.AttSecurityNone, []byte("bts"))

			btstack.StartAdvertising("btstack", btstack.AttDbUtilGetAddress(), nil)
		}
	case *btstack.EventLeConnectionCompletePacket:
		fmt.Printf("New connection: Role: %d, Handle: 0x%04x, Interval: %.2f, Latency: %d\n",
			packet.Role(), packet.Handle(), packet.Interval(), packet.Latency())
		time.AfterFunc(time.Second, func() {
			btstack.GapReadRssi(packet.Handle())
		})
		btstack.StopAdvertising()
	case *btstack.EventRssiMeasurementPacket:
		fmt.Printf("Read rssi: Con handle: 0x%04x, Rssi: %d\n", packet.Handle(), packet.Rssi())
	case *btstack.EventDisconnectionCompletePacket:
		fmt.Printf("Disconnect Handle: 0x%04x, Status: 0x%02x, Reason: 0x%02x\n",
			packet.Handle(), packet.Status(), packet.Reason())
	}
}

func stdinProcess(cmd byte) {
	if cmd == 'q' {
		btstack.HciClose()
		os.Exit(0)
	}
}
